﻿@model Task

@{
    // Check Layout
    if(CompareUtility.IsStringsEqual(Request["EmptyLayout"], "true") 
        || CompareUtility.IsStringsEqual(Request["NoLayout"], "true"))
    {
        Layout = "~/Views/Shared/_EmptyLayout.cshtml";
        ViewBag.EmptyLayout = true;
        
    }
    
    // Check Main Model
    if(Model == null){
        @: ไม่พบข้อมูล @ViewBag.TaskId
        return;
    }
    
    // Declare Variable
    Employee currentApproverEmployee = null;
    IEnumerable<Employee> emps;
    GERPContext context;
    int curStep = 0;
    int allStep = 0;
    decimal progressDecimal;
    decimal progressPercent;
    ApproveProcess appPrc;
    Employee completerApprover;
    var sApprove = new KPIS.GERP.WEB.GIMS.SysApprovalService.SysApprovalServiceClient();
    ViewBag.Title = "คำขออนุมัติ [" + Model.Title + "]";
    IEnumerable<TaskHistory> ths;
    TaskHistory lastestTh;
    
    // Fetch data
    context = new GERPContext(true);
    emps = context.Employees.Where(o => o.RecordStatus != "D");
    Model.ApplyToEmployee = emps.FirstOrDefault(o => o.EmpId == Model.ApplyToEmpId);
    Model.TaskHistories = context.TaskHistories.Include(o => o.ApprovePathSimulate.ApprovePath)
        .Where(o=>o.RecordStatus != "D" && o.TaskId==Model.TaskId).ToList();
    Model.CurrentTaskHistory = Model.TaskHistories
        .FirstOrDefault(o => o.TaskHistoryId == Model.CurrentTaskHistoryId && o.RecordStatus != "D");
    appPrc = sApprove.SelectApproveProcess(0).FirstOrDefault(o => o.AppPrcId == Model.AppPrcId);
    completerApprover = context.Employees.FirstOrDefault(o => o.EmpId == Model.CompletedBy);
    // Find last
    ths = Model.TaskHistories.OrderByDescending(o => o.TaskHistoryId); 
    lastestTh = !Model.Completed ? ths.Skip(1).FirstOrDefault() : ths.FirstOrDefault();
    ths = Model.TaskHistories.OrderBy(o => o.TaskHistoryId);
    if(Model.CurrentTaskHistory != null)
    {
        currentApproverEmployee = context.Employees.FirstOrDefault(o => o.PosId == Model.CurrentTaskHistory.ApproverPosId);
    }
    if(!Model.Completed)
    {
        curStep = Model.CurrentTaskHistory == null ? -1 : Model.CurrentTaskHistory.StepNo.Value;
    }
    // Find heightest Step No in Simulate
    allStep = Model.Simulates.Select(sim => sim.SimulateStepNo).Concat(new[]{allStep}).Max();
    // Percent complete of task
    progressDecimal = allStep == 0 ? 0 : (((decimal) (curStep - 1)/(decimal) allStep)*100);
    progressPercent = Math.Round(progressDecimal, 0);
    
    ViewBag.emps = emps;
    ViewBag.AppPrc = appPrc;
    ViewBag.currentApproverEmployee = currentApproverEmployee;
    ViewBag.ths = ths;
    ViewBag.context = context;
    ViewBag.lastestTh = lastestTh;


    var strTaskCode = "";
    var strTaskRefCode = "";
    var strResult = "";
}

<div class="row-fluid">
    <div class="span12">
        
           
        @{
            var posId = GimsMembership.User.Employee.PosId;
            var empId = GimsMembership.CurrentEmpId;
            List<int?> posIds = new List<int?> { posId.Value };
            List<int?> empIds = new List<int?> { empId };
            var db = new GERPContext(true);
            foreach (var wod in db.MpPositionWorkOnDuties
                .Where(o => o.RecordStatus == "A" &&
                            o.StartDate <= DateTime.Now &&
                            o.EndDate >= DateTime.Now &&
                            o.ByEmpSeq == empId))
            {
                var emp = emps.FirstOrDefault(o => o.PosId == wod.ToPosSeq && o.RecordStatus != "D");
                if (emp != null && emp.PosId.HasValue && !posIds.Contains(emp.PosId.Value))
                {
                    posIds.Add(emp.PosId);
                    empIds.Add(emp.EmpId);
                }
            }
            posIds.RemoveAll(o => !o.HasValue);
            bool isCreatedByCurrentEmployeeOrWod = empIds.Contains(Model.CreatedBy);
            bool isApplyToCurrentEmployeeOrWod = empIds.Contains(Model.ApplyToEmpId);
            bool isApproverIsCurrentEmployee = Model.CurrentTaskHistory != null && posIds.Contains(Model.CurrentTaskHistory.ApproverPosId);
        }

        @if (!Model.Completed && (isCreatedByCurrentEmployeeOrWod || isApplyToCurrentEmployeeOrWod || isApproverIsCurrentEmployee))
        {
            <div class="widget-box">
             
                @using (Html.BeginForm("TakeAction", "Task", FormMethod.Post, new { @class = "form-horizontal" }))
                {
                    bool noLayout = ViewBag.nolayout == true || ViewBag.EmptyLayout == true;
                    @Html.Hidden("NoLayout", noLayout)
                    @Html.HiddenFor(o => o.TaskId)
                    @Html.Hidden("taskHistoryId", Model.CurrentTaskHistoryId)
                    <input type="hidden" name="action" id="action" value=""/>
                    
                    <table width="100%" class="DivInfo" style="height:48px">
                        <tr>
                            <td  width="120px">&nbsp;&nbsp;<strong>ตอบกลับ : </strong></td>
                            <td style="padding: 0 0 0 10px">
                                @{
                                    var disabledClass = Model == null || Model.RecordStatus == "D" ? " disabled='disabled' " : "";
                                }
                                @if (Model == null || Model.RecordStatus == "D")
                                {
                                    <span style="font-style: italic; font-size: x-small; color:orange;">คำขออนุมัตินี้ถูกลบแล้ว ไม่สามารถกระทำการต่อได้</span>
                                }
                                
                                @if (Model.CurrentTaskHistory != null &&
                                     posIds.Contains(Model.CurrentTaskHistory.ApproverPosId) &&
                                     Model.CurrentTaskHistory.IsApproveAble)
                                {
                @*<option value="1">อนุมัติ</option>*@ 
    <button name="action" id="action" type="submit" value="1" class="buttonAsLink" @disabledClass > อนุมัติ</button> 
                                }

                                @if (Model.CurrentTaskHistory != null &&
                                     posIds.Contains(Model.CurrentTaskHistory.ApproverPosId) &&
                                     Model.CurrentTaskHistory.IsForwardable)
                                {
                                    bool foundCurrentSimulate = false;
                                    bool foundNextSimulate = false;
                                    foreach (var th in Model.Simulates)
                                    {
                                        if (foundCurrentSimulate)
                                        {
                                            foundNextSimulate = true;
                                            break;
                                        }
                                        if (Model.CurrentTaskHistory.SimId == th.SimId)
                                        {
                                            foundCurrentSimulate = true;
                                        }
                                    }
                @*
                    <option value="2" @(foundNextSimulate ? "" : "disabled='disabled'")>
                        ส่งต่อ
                        @{
                            var currentSimulate = Model.CurrentTaskHistory.SimId;
                            var sims = Model.Simulates.Where(o => !o.IsForNotice).OrderBy(o => o.SimulateStepNo);
                            var nextSim = sims.SkipWhile(o => o.SimId != currentSimulate).Skip(1).FirstOrDefault();
                            if (nextSim != null)
                            {
                                @:ไปที่@(nextSim.ApproverPosition.Name) (ขั้นตอนที่ @nextSim.SimulateStepNo)
                            }
                        }
                    </option>*@
                                    <button name="action" id="action" type="submit" value="2" class="buttonAsLink" @(foundNextSimulate ? "" : "disabled='disabled'")>
                                        ส่งต่อ
                                        @{
                                            var currentSimulate = Model.CurrentTaskHistory.SimId;
                                            var sims = Model.Simulates.Where(o => !o.IsForNotice).OrderBy(o => o.SimulateStepNo);
                                            var nextSim = sims.SkipWhile(o => o.SimId != currentSimulate).Skip(1).FirstOrDefault();
                                            if (nextSim != null)
                                            {
                                                @:ไปที่@(nextSim.ApproverPosition.Name) (ขั้นตอนที่ @nextSim.SimulateStepNo)
                                            }
                                        }
                                    </button>
                                }
                                @if (Model.CurrentTaskHistory != null &&
                                     posIds.Contains(Model.CurrentTaskHistory.ApproverPosId) &&
                                     Model.CurrentTaskHistory.IsRejectable)
                                {
                                    <button name="action" id="action" type="submit" value="3" class="buttonAsLink" 
onclick="javascript: if ($('#Remarks').val()) { return true; } else { alert('กรุณากรอกหมายเหตุในช่องความเห็นเพิ่มเติมก่อน'); return false;}">ไม่ผ่านการอนุมัติ</button>
                @*<option value="3">ไม่ผ่านการอนุมัติ</option>*@
                                }
                                @if (Model.CurrentTaskHistory != null &&
                                     posIds.Contains(Model.CurrentTaskHistory.ApproverPosId) &&
                                     Model.CurrentTaskHistory.IsSendBackable)
{
    <button name="action" id="action" type="submit" value="6" class="buttonAsLink"
            onclick="javascript: if ($('#Remarks').val()) { return true; } else { alert('กรุณากรอกหมายเหตุในช่องความเห็นเพิ่มเติมก่อน'); return false;}">
        ส่งกลับไปที่ผู้ทำคำขอให้แก้ไข
    </button>





                              
                @*<option value="6">ส่งกลับไปที่ผู้ทำคำขอให้แก้ไข</option>*@
}@if (!Model.Completed && (empIds.Contains(Model.CreatedBy) ||
                                                           empIds.Contains(Model.ApplyToEmpId)))
{
    <button name="action" id="action" type="submit" value="8" class="buttonAsLink"
            onclick="javascript: if ($('#Remarks').val()) { return true; } else { alert('กรุณากรอกหมายเหตุในช่องความเห็นเพิ่มเติมก่อน'); return false;}">
        ส่งกลับไปที่ผู้ทำคำขอให้แก้ไข
    </button>



                   
    
    
                @*<option value="8">ยกเลิกคำขอที่คุณสร้างไว้</option>*@
}
                                @if (!Model.Completed &&
                                     (empIds.Contains(Model.CreatedBy) ||
                                      empIds.Contains(Model.ApplyToEmpId)) &&
                                     Model.IsInRequiringSendBack)
{
    <button name="action" id="action" type="submit" value="10" class="buttonAsLink"
            onclick="javascript: if ($('#Remarks').val()) { return true; } else { alert('กรุณากรอกหมายเหตุในช่องความเห็นเพิ่มเติมก่อน'); return false;}">
        ส่งคืนให้พิจารณาต่อ
    </button> 
                @*<option value="10">ส่งคืนให้พิจารณาต่อ</option>*@
}
                            </td>
                        </tr>
                    </table>
                    <table style="width:100%">
                        <tr>
                            <td style="font-weight: bold; width:120px">หัวข้อคำขอ</td>
                            <td><input class="span12" id="title" name="title" placeholder="หัวข้อคำขอ" type="text" value="@Model.Title" style="padding-top: 4px"></td>
                        </tr>
                        <tr>
                            <td style="font-weight: bold">ความเห็นเพิ่มเติม</td>
                            <td>
                                <textarea class=" span12 autosize-transition" id="Remarks" name="Remarks" style="padding-top: 4px" placeholder="ความเห็นเพิ่มเติม"></textarea>
                                <span id="lblWarning2" class="text-error">*กรุณากรอกหมายเหตุลงในช่อง</span> 
                            </td>
                        </tr>
                    </table> 
                }
            </div>
            
                
                <i>
                    กำลังทำการในตำแหน่ง
                    @{
            int? posId1;
            var loginEmp = GimsMembership.Employee;
            if (string.IsNullOrWhiteSpace(Request["sendId"]))
            {
                posId1 = loginEmp.PosId;
            }
            else
            {
                var wod = db.MessageSends.Find(Convert.ToInt32(Request["sendId"]));
                posId1 = wod.ToPosId;
            }

            if (!posId1.HasValue)
            {
                @:-
                            }
            else
            {
                var emp1 = db.Employees.FirstOrDefault(o => o.RecordStatus != "D" && o.PosId == posId1);

                if (emp1 != null)
                {
                    @:@(emp1 == null ? "-" : emp1.Position.PosNo + " - " + emp1.Position.Name + "  " + emp1.FullName)
                                }

                if (loginEmp.PosId != posId1)
                {
                    @:(รักษาการณ์โดย @(loginEmp.Position.PosNo + " - " + loginEmp.Position.Name + "  " + loginEmp.FullName))
                                }
            }
                    }
                </i>
        }
        
        <br/>
        <hr/>
        
        @if (!CompareUtility.IsStringsEqual(Request["EmptyLayout"], "true") && !CompareUtility.IsStringsEqual(Request["NoLayout"], "true"))
        {
            <div class="block-button-menu-above">
                @Html.ButtonViewAll(new { EmptyLayout = ViewBag.EmptyLayout })
            </div>
        }

        @if (!string.IsNullOrWhiteSpace(ViewBag.commandActionResult))
        {
            <div class="alert alert-block alert-success">
                <button type="button" class="close" data-dismiss="alert">
                    <i class="icon-remove"></i>
                </button>
                @ViewBag.commandActionResult
            </div>
        }
        @if (!string.IsNullOrWhiteSpace(ViewBag.commandActionErrorResult))
        {
            <div class="alert alert-block alert-error">
                <button type="button" class="close" data-dismiss="alert">
                    <i class="icon-remove"></i>
                </button>
                @ViewBag.commandActionErrorResult
            </div>
        }


        <div class="alert @(Model.Completed?"alert-info":"warning")">
            <button type="button" class="close" data-dismiss="alert">
                <i class="icon-remove"></i>
            </button>
            <strong>สถานะของคำขอ</strong>
            <span class="grey">
                @Model.StatusText
            </span>

            @if (lastestTh != null && !string.IsNullOrWhiteSpace(lastestTh.Remark))
            {
                <br />
                <strong>หมายเหตุล่าสุด:</strong>
                <span class="grey">
                    @lastestTh.Remark
                </span>
            }
        </div>


 
        

        <div class="widget-box">
            <div class="widget-header header-color-blue2">
                <h4 class="lighter smaller">
                    @{
                        strTaskCode = null;//!string.IsNullOrEmpty(Model.Code) ? "<span title='รหัสอ้างอิงคำขอ'><strong>" + Model.Code + "</strong></span>" : "";
                        strTaskRefCode = !string.IsNullOrWhiteSpace(Model.RefCode) ? "<span title='รหัสอ้างอิงที่เกี่ยวข้องกับคำขอ' style='color:yellow'>" + Model.RefCode + "</span>" : "";
                        strResult = "";
                        if(!string.IsNullOrWhiteSpace(strTaskCode) && !string.IsNullOrWhiteSpace(strTaskRefCode))
                        {
                            strResult = string.Format("{0} [{1}] : ", strTaskCode, strTaskRefCode);
                        } else if(!string.IsNullOrWhiteSpace(strTaskCode))
                        {
                            strResult = string.Format("{0} : ", strTaskCode);
                        } else if(!string.IsNullOrWhiteSpace(strTaskRefCode))
                        {
                            strResult = string.Format("[{0}] : ", strTaskRefCode);
                        } else
                        {
                            strResult = "";
                        }

                        strResult += appPrc != null ? string.Format(" <span title='หัวข้อคำขอ'>{1}</span> <i title='ชื่อประเภทคำขอ'>[{0}]</i>", appPrc.Name, Model.Title) : "";
                    }
                    @Html.Raw(strResult)
                </h4>
            </div>
            <div class="widget-body">
                <div class="widget-body-inner">
            
                    <div class="tabbable">
                
                        <ul class="nav nav-tabs" id="myTab2">
                            <li class="active">
                                <a data-toggle="tab" href="#RelatedPage">
                                    ข้อมูลที่เกี่ยวข้อง
                                </a>
                            </li>
                            <li>
                                <a data-toggle="tab" href="#General">ทั่วไป</a>
                            </li>
                            <li>
                                <a data-toggle="tab" href="#Details">ขั้นตอนตามปกติของคำขอ</a>
                            </li> 
                        </ul>

                        <div class="tab-content">
                            <div id="RelatedPage" class="tab-pane in active">
                                @Html.Partial("_DetailTabRelatedPage", Model)
                            </div>
                            <div id="General" class="tab-pane">
                                @Html.Partial("_DetailTabGeneral", Model)
                            </div>
                    
                            <div id="Details" class="tab-pane">
                                @{
                                    ViewBag.Task = Model;
                                }
                                @Html.Partial("_DetailTabApprovePath")
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
        

    <style>
        .buttonAsLink {
            background: none !important;
            border: none;
            padding: 0 !important;
            font: inherit;
            /*border is optional*/
            color: blue;
            cursor: pointer;
            margin-right: 10px;
            padding-right: 10px !important;
            border-right: solid 1px white ;
        }
        .DivInfo {
            background-color: #D8DFEA;
            padding-bottom: 10px;
            padding-top: 10px;
            padding-left: 10px;
        }
    </style>
    
    @section scripts
    {
        <script>
            $(function () {
                var lastHeight1 = 0, curHeight1 = 0, $frame1 = $('#iframe1');
                setInterval(function () {
                    curHeight1 = $frame1.contents().find('body').height() + 50;
                    if (curHeight1 != lastHeight1) {
                        $frame1.css('height', (lastHeight1 = curHeight1) + 'px');
                    }
                }, 500);

                $('button[name=action]').click(function() {
                    $('#action').val($(this).val());
                });
            });

            $("form").not("#formsearch").submit(function (e) {
                e.preventDefault();
                var currentForm = this;
                bootbox.confirm("ท่านต้องการยืนยัน ใช่หรือไม่", function (result) {
                    if (result) {
                        currentForm.submit();
                    }
                });
            });

            $('#lblWarning1').hide();
            $('#lblWarning2').hide();
            var warnToMakeRemark = function() {
                switch ($('#action').val()) {
                    case '3':// ไม่ผ่านการอนุมัติ
                    case '6':// ส่งกลับให้แก้ไข
                    case '8':// ยกเลิก
                    case '10':// ส่งคืนให้พิจารณาต่อ
                        $('#lblWarning1').show();
                        $('#lblWarning2').show();
                    break;
                    default:
                        $('#lblWarning1').hide();
                        $('#lblWarning2').hide();
                }
            };
            $('#action').on('change', warnToMakeRemark);
            $('#action').val($("#action option:first").val());
            warnToMakeRemark();
            
            $('#table').dataTable();

            $('table th input:checkbox').on('click', function () {
                var that = this;
                $(this).closest('table').find('tr > td:first-child input:checkbox')
                    .each(function () {
                        this.checked = that.checked;
                        $(this).closest('tr').toggleClass('selected');
                    });

            });

            $('[data-rel=tooltip]').tooltip();

            $("#form").submit(function (e) {
                e.preventDefault();
                var currentForm = this;
                bootbox.confirm("คุณแน่ใจหรือไม่", function (c) {
                    if (c) {
                        $.ajax({
                            url: "@Url.Action("DeleteAll")",
                            type: "post",
                            dataType: "json",
                            data: $(currentForm).serialize(),
                            context: document.body,
                            success: function (s) {
                                if (s.success) {
                                    location.reload();
                                }
                            },
                            error: function (xhr, status, error) {
                                alert("Status: " + status + ", Error: " + error + ", XHR: " + xhr.readyState);
                            },
                            statusCode: {
                                404: function () {
                                    alert("Page not found");
                                }
                            }
                        });
                    }
                });
                return false;
            });

            $('textarea[class*=autosize]').autosize({ append: "\n" });

        </script>
    } </div> 

    